require 'right_aws'
module Xlr8
  class Proxy
    def initialize( access_key_id, secret_access_key, bucket )
      @access_key_id = access_key_id
      @secret_access_key = secret_access_key
      # TODO:
      # make sure that s3 lib is loaded w/ support for 
      # - persistent connections ( i think right_aws might do this by default?)
      # - large data txfers
      
      @s3 = RightAws::S3.new( @access_key_id, @secret_access_key )
      @bucket = find_or_create_bucket( bucket )
      @acf = RightAws::AcfInterface.new( @access_key_id, @secret_access_key )
    end


    def to_s3( key, data, meta_headers, permissions, headers )
      @bucket.put( key, data, meta_headers, permissions, headers )
    end

    def edge_cache( origin, options=nil )
      options ||= {}
      enable_distribution = true
      cnames = options[:cnames] || nil
      caller_reference = options[:caller_reference] || origin
      params = [origin, 'xlr8 distribution', enable_distribution, cnames, caller_reference]
      begin
        @acf_info = @acf.create_distribution( *params )
      rescue
        puts "got error #{$!.inspect} for request #{params.inspect}"
        raise
      end
      return { :domain_name => @acf_info[:domain_name], 
        :active => ( :deployed == @acf_info[:status].downcase.to_sym ),
        :details => @acf_info.dup
      }
    end

    private
    def find_or_create_bucket( bucket )
      create_if_not_found = true
      bucket = @s3.bucket( bucket, create_if_not_found, 'public-read' )
    end

  end
end # module Xlr8
